package net.sourceforge.simcpux;

import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.library.sharehelper.WXShareHelper;
import com.library.sharehelper.base.BaseShareActivity;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelmsg.ShowMessageFromWX;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class LoginActivity extends BaseShareActivity {

    private static final String TAG = LoginActivity.class.getSimpleName();
    protected OkHttpClient client;//网络请求的client


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        findViewById(R.id.login_with_wx).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WXShareHelper.getInstance().sendLogin(LoginActivity.this);
            }
        });
        client = new OkHttpClient();
    }

    @Override
    public void onResp(BaseResp baseResp) {
        super.onResp(baseResp);
        if (baseResp.errCode == BaseResp.ErrCode.ERR_OK) {
            //发送成功
            SendAuth.Resp sendResp = (SendAuth.Resp) baseResp;
            String code = sendResp.code;
            getAccessToken(code);
        }
    }

    /**
     * 获取openid accessToken值用于后期操作
     *
     * @param code 请求码
     */
    private void getAccessToken(final String code) {
        final String path = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
                + Constants.APP_ID
                + "&secret="
                + Constants.APP_SECRET
                + "&code="
                + code
                + "&grant_type=authorization_code";
        Log.d("getAccessToken", path);
        Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                FormBody formBody = new FormBody.Builder()
                        .add("", "")
                        .build();
                String result = initHttp(path, formBody);
                Log.d(TAG, "wubaojie>>>call: " + result);
                subscriber.onNext(result);
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable throwable) {
                throwable.printStackTrace();
            }

            @Override
            public void onNext(String result) {
                JSONObject jsonObject;
                try {
                    jsonObject = new JSONObject(result);
                    String openid = jsonObject.getString("openid").trim();
                    String access_token = jsonObject.getString("access_token").trim();
                    getUserMesg(access_token, openid);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 获取微信的个人信息
     *
     * @param access_token
     * @param openid
     */
    private void getUserMesg(final String access_token, final String openid) {
        final String path = "https://api.weixin.qq.com/sns/userinfo?access_token="
                + access_token
                + "&openid="
                + openid;
        Log.d(TAG, "getUserMesg：" + path);
        Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                FormBody formBody = new FormBody.Builder()
                        .add("", "")
                        .build();
                String result = initHttp(path, formBody);
                Log.d(TAG, "wubaojie>>>call: " + result);
                subscriber.onNext(result);
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable throwable) {
                throwable.printStackTrace();
            }

            @Override
            public void onNext(String result) {
                JSONObject jsonObject;
                try {
                    jsonObject = new JSONObject(result);
                    String nickname = jsonObject.getString("nickname");
                    int sex = Integer.parseInt(jsonObject.get("sex").toString());
                    String headimgurl = jsonObject.getString("headimgurl");

                    Log.d(TAG, "用户基本信息:" + "nickname:" + nickname + "sex:" + sex + "headimgurl:" + headimgurl);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * @param url
     * @param formBody
     */
    protected String initHttp(String url, FormBody formBody) {
        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();
        Log.e(TAG, "wangtao---->>>:网路请求地址:" + url);
        try {
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                return response.body().string();
            } else {
                return "请求失败";
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "请求失败";
    }

    @Override
    protected void goToGetMsg() {

    }

    @Override
    protected void goToShowMsg(ShowMessageFromWX.Req baseReq) {

    }
}
